# models.py
from extension import db
from datetime import datetime


class Book(db.Model):
    __table_name = "book"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    book_number = db.Column(db.String(255), nullable=False)
    book_name = db.Column(db.String(255), nullable=False)
    book_type = db.Column(db.String(255), nullable=False)
    book_price = db.Column(db.Float, nullable=False)
    author = db.Column(db.String(255))
    book_press = db.Column(db.String(255))
    publication_date = db.Column(db.DateTime, nullable=True)

    @staticmethod
    def init_db():
        engine = db.get_engine()
        inspector = db.inspect(engine)

        if not inspector.has_table('book'):
            db.create_all()

            book_list = [
                (1, '001', '小城与不确定性的墙', '小说', 89.9, '[日] 村上春树', '江苏凤凰文艺出版社',
                 '2024-10-1'),
                (2, '002', '恶女的告白', '文学', 59.9, '[日] 叶真中显', '中国友谊出版公司',
                 '2024-9-5'),
            ]
            for item in book_list:
                book = Book(
                    book_number=item[1],
                    book_name=item[2],
                    book_type=item[3],
                    book_price=item[4],
                    author=item[5] if item[5] else None,
                    book_press=item[6] if item[6] else None,
                    publication_date=datetime.strptime(
                        item[7], '%Y-%m-%d') if item[7] else None)
                db.session.add(book)

            db.session.commit()
